﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spider.Mode;
using TdxHq.Connect;
using TdxHq.Invoker;

namespace TdxHq
{
    public class Quote
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("Quote");
        /// <summary>
        /// 获取所有A股代码  耗时1s
        /// </summary>
        /// <returns></returns>
        public static List<Stkinfo> TdxGetStkcode(TdxConnection tdxConnection)
        {
            StringBuilder sErrInfo = new StringBuilder(256);
            StringBuilder sResult = new StringBuilder(1024 * 1024);
            //byte markettype = Stkcode.Substring(7, 2) == "SH" ? (byte)1 : (byte)0;

            short Result = new short();
            List<Stkinfo> Trans = new List<Stkinfo>();
            bool bRet;
            short count = 0;

            ///获取深A代码
            QuoteDelegate.TdxHq_GetSecurityCount getSecurityCountDelegate =
                (QuoteDelegate.TdxHq_GetSecurityCount) tdxConnection.Invoker.Invoke("TdxHq_GetSecurityCount",
                    typeof(QuoteDelegate.TdxHq_GetSecurityCount));
            bRet = getSecurityCountDelegate(0, ref Result, sErrInfo);
            count = 1000;
            for (int i = 0; i <= Result / 1000; i++)
            {
                QuoteDelegate.TdxHq_GetSecurityList getSecurityList =
                    (QuoteDelegate.TdxHq_GetSecurityList) tdxConnection.Invoker.Invoke("TdxHq_GetSecurityList",
                        typeof(QuoteDelegate.TdxHq_GetSecurityList));
                getSecurityList(0, (short) (i * 1000), ref count, sResult, sErrInfo);

                var a = sResult.ToString().Split('\n').ToList();
                a.RemoveAt(0);
                foreach (var item in a)
                {
                    var b = item.Split('\t');
                    if (b[0].StartsWith("300") || b[0].StartsWith("00"))
                        Trans.Add(new Stkinfo
                        {
                            Stkcode = b[0],
                            StkBaseVol = Convert.ToInt16(b[1]),
                            Stkname = b[2],
                            Save1 = b[3],
                            Save2 = b[4],
                            preclose = Convert.ToDecimal(b[5]),
                            Save3 = b[6],
                            Type = "0"
                        });
                }
            }

            ///获取沪A代码
            QuoteDelegate.TdxHq_GetSecurityCount getSecurityCount =
                (QuoteDelegate.TdxHq_GetSecurityCount) tdxConnection.Invoker.Invoke("TdxHq_GetSecurityCount",
                    typeof(QuoteDelegate.TdxHq_GetSecurityCount));
            bRet = getSecurityCount(1, ref Result, sErrInfo);
            for (int i = 0; i <= Result / 1000; i++)
            {
                QuoteDelegate.TdxHq_GetSecurityList getSecurityList =
                    (QuoteDelegate.TdxHq_GetSecurityList) tdxConnection.Invoker.Invoke("TdxHq_GetSecurityList",
                        typeof(QuoteDelegate.TdxHq_GetSecurityList));
                getSecurityList(1, (short) (i * 1000), ref count, sResult, sErrInfo);
                var a = sResult.ToString().Split('\n').ToList();
                a.RemoveAt(0);
                foreach (var item in a)
                {
                    var b = item.Split('\t');
                    if (b[0].StartsWith("60"))
                        Trans.Add(new Stkinfo
                        {
                            Stkcode = b[0],
                            StkBaseVol = Convert.ToInt16(b[1]),
                            preclose = Convert.ToDecimal(b[5]),
                            Stkname = b[2],
                            Type = "1"
                            //Save1 = b[3],
                            //Save2 = b[4],                         
                            //Save3 = b[6]
                        });
                }
            }
            Log.Error(sErrInfo.ToString() == "" ? "获取全A市场代码--成功" : "获取全A市场代码--失败");
            return Trans;
        }

        /// <summary>
        /// 返回批量行情 入参为wind 代码格式
        /// </summary>
        /// <param name="tdxConnection"></param>
        /// <param name="stklist"></param>
        /// <returns></returns>
        public static List<QuoteRt> Quotes(TdxConnection tdxConnection, List<string> stklist)
        {
            StringBuilder sErrInfo = new StringBuilder(256);
            StringBuilder sResult = new StringBuilder(1024 * 1024);
            List<QuoteRt> quote = new List<QuoteRt>();
            var Zqdm = stklist.Select(p => p.Substring(0, 6)).ToArray();
            var Market = stklist.Select(p => p.EndsWith("SZ") ? (byte) 0 : (byte) 1).ToArray();
            var Count = (short) Zqdm.Count();
            //byte[] Market = {1};
            //string[] Zqdm = {"600000"};
            //short Count = 1;
            //获取10档行情

            bool success = tdxConnection.GetSecurityQuotes(Market, Zqdm, ref Count, sResult, sErrInfo);

            if (sErrInfo.ToString() != ""|| !success)
            {
                Log.Error("L2Quotes--失败");
                return null;
            }

            //获取5档行情
            //bool bool12 = TradeX.TdxL2Hq_GetSecurityQuotes(Market, Zqdm, ref Count, sResult, sErrInfo);
            var a = sResult.ToString().Split('\n').ToList();
            a.RemoveAt(0);
            foreach (var item in a)
            {
                var b = item.Split('\t');
                quote.Add(new QuoteRt
                {
                    Market = b[0],
                    StkCode = b[1],
                    Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Vitality = Convert.ToDouble(b[2]),
                    LastPrice = Convert.ToDouble(b[3]),
                    PreClose = Convert.ToDouble(b[4]),
                    Open = Convert.ToDouble(b[5]),
                    High = Convert.ToDouble(b[6]),
                    Low = Convert.ToDouble(b[7]),
                    Bid1 = Convert.ToDouble(b[17]),
                    Ask1 = Convert.ToDouble(b[18]),
                    Bsize1 = Convert.ToInt32(b[19])
                });
            }
            return quote;
        }

        ///  <summary>
        /// 返回批量行情  最大值50
        ///  </summary>
        /// <param name="tdxConnection"></param>
        /// <param name="stklist"></param>
        ///   0市场	1代码	2活跃度	3现价	4昨收	5开盘	6最高	7最低	8时间	9保留	10总量	11现量	12总金额	13内盘	14外盘	15保留	16保留	17买一价	18卖一价	19买一量	20卖一量	21买二价	22卖二价	23买二量	24卖二量	25买三价	26卖三价	27买三量	28卖三量	29买四价	30卖四价	31买四量	32卖四量	33买五价	34卖五价	35买五量	36卖五量	37保留	38保留	39保留	40保留	41保留	42涨速	43活跃度
        ///  <returns></returns>
        public static List<QuoteRt> Quotes(TdxConnection tdxConnection, List<Stkinfo> stklist)
        {
            StringBuilder sErrInfo = new StringBuilder(256);
            StringBuilder sResult = new StringBuilder(1024 * 1024);
            List<QuoteRt> quote = new List<QuoteRt>();
            var Zqdm = stklist.Select(p => p.Stkcode).ToArray();
            var Market = stklist.Select(p => Convert.ToInt16(p.Type) == 0 ? (byte) 0 : (byte) 1).ToArray();
            var Count = (short) Zqdm.Count();

            bool success = tdxConnection.GetSecurityQuotes(Market, Zqdm, ref Count, sResult, sErrInfo);
            if (sErrInfo.ToString() != "" || !success)
            {
                Log.Error("L2Quotes--失败");
                return null;
            }

            //获取5档行情
            //bool bool12 = TradeX.TdxL2Hq_GetSecurityQuotes(Market, Zqdm, ref Count, sResult, sErrInfo);
            var a = sResult.ToString().Split('\n').ToList();
            a.RemoveAt(0);
            //foreach (var item in a)
            //{
            //    var b = item.Split('\t');
               
            //    quote.Add(new QuoteRt
            //    {
            //        Market = b[0],
            //        StkCode = b[1],
            //        Vitality = Convert.ToDouble(b[2]),
            //        LastPrice = Convert.ToDouble(b[3]),
            //        Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        PreClose = Convert.ToDouble(b[4]),
            //        Open = Convert.ToDouble(b[5]),
            //        High = Convert.ToDouble(b[6]),
            //        Low = Convert.ToDouble(b[7]),
            //        Bid1 = Convert.ToDouble(b[17]),
            //        VolAll = Convert.ToDouble(b[10]),
            //        Ask1 = Convert.ToDouble(b[18]),
            //        Bsize1 = Convert.ToInt32(b[19]),
            //        Asize1 = Convert.ToInt32(b[20])
            //    });
            //}
            for (var i = 0; i < a.Count; i++)
            {
                var b = a[i].Split('\t');

                quote.Add(new QuoteRt
                {
                    Market = b[0],
                    StkCode = b[1],
                    StkName = stklist[i].Stkname,
                    Vitality = Convert.ToDouble(b[2]),
                    LastPrice = Convert.ToDouble(b[3]),
                    Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    PreClose = Convert.ToDouble(b[4]),
                    Open = Convert.ToDouble(b[5]),
                    High = Convert.ToDouble(b[6]),
                    Low = Convert.ToDouble(b[7]),
                    Bid1 = Convert.ToDouble(b[17]),
                    VolAll = Convert.ToDouble(b[10]),
                    Ask1 = Convert.ToDouble(b[18]),
                    Bsize1 = Convert.ToInt32(b[19]),
                    Asize1 = Convert.ToInt32(b[20])
                });
            }
            foreach (var item in a)
            {
                var b = item.Split('\t');

                quote.Add(new QuoteRt
                {
                    Market = b[0],
                    StkCode = b[1],
                    Vitality = Convert.ToDouble(b[2]),
                    LastPrice = Convert.ToDouble(b[3]),
                    Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    PreClose = Convert.ToDouble(b[4]),
                    Open = Convert.ToDouble(b[5]),
                    High = Convert.ToDouble(b[6]),
                    Low = Convert.ToDouble(b[7]),
                    Bid1 = Convert.ToDouble(b[17]),
                    VolAll = Convert.ToDouble(b[10]),
                    Ask1 = Convert.ToDouble(b[18]),
                    Bsize1 = Convert.ToInt32(b[19]),
                    Asize1 = Convert.ToInt32(b[20])
                });
            }

            return quote;
        }
    }
}